<!--
 * @Descripttion: 
 * @version: 
 * @Author: 川杨
 * @Date: 2022-02-28 16:15:13
 * @LastEditors: 川杨
 * @LastEditTime: 2022-07-29 09:41:00
-->
<template>
  <div :class="['biz-user-card',showIm?'biz-user-card-im':'']" :style="style" v-show="show" v-loading="!userData">
    <div v-if="show&&userData">
      <div class="biz-user-card-header">
        <img :src="head(userData.head)" alt="" class="avatar">
        <div class="state">
          <div class="state-top">
            <template v-if="isOpenData">
              <open-data type='userName' :openid="userData.staffId"></open-data>
            </template>
            <span class="user-name" v-else>{{userData.userName||userData.displayName||userData.LoginName||''}}</span>
            <div class="work-state">
              <template v-if="userData.state&&userData.beOnTheJob">
                <i class="contact-user-state-icon" :style="{backgroundColor: stateColor[userData.state]}"></i> 
                <span>{{userData.state}}</span>
              </template>
              <template v-if="!userData.beOnTheJob">
                <span class="off-job">{{$t('common.base.deleted')}}</span>
              </template>    
            </div>
          </div>
          <div class="state-bottom">{{userData.company}}</div>
        </div>
        <div class="right-arrow" v-if="userData.showUserDetail" @click="lookDynamics"><i class="iconfont icon-right"></i></div>
      </div>
      <div class="biz-user-card-main">
        <div class="biz-user-info" v-if="userData.showCalendar">
          <div class="user-form-item">
            <div class="user-card-label">{{$t('common.schedule.title')}}：</div>
            <div class="user-card-content" @click="lookCalendar">
              <span class="look-calendar">{{$t('common.schedule.viewStatus')}}</span>
            </div>
          </div>
        </div>
        <div class="calendar-devider" v-if="userData.showCalendar"></div>
        <div class="biz-user-info">
          <div class="user-form-item" v-if="userData.phone&&userData.phone.show">
            <div class="user-card-label">{{$t('common.label.phone')}}：</div>
            <div class="user-card-content">{{userData.phone.fieldValue}}</div>
          </div>
          <div class="user-form-item" v-if="userData.email&&userData.email.show">
            <div class="user-card-label">{{$t('common.label.email')}}：</div>
            <div class="user-card-content">{{userData.email.fieldValue}}</div>
          </div>
          <template v-if="userData.departmentList&&userData.departmentList.show">
            <div class="user-form-item" v-for="(tag,index) in userData.departmentList.fieldValues" :key="index">
              <div class="user-card-label">{{$t('common.label.department')}}：</div>
              <div class="user-card-content">{{tag}}</div>
            </div>
          </template>
          <div class="user-form-item" v-if="userData.roleList&&userData.roleList.show">
            <div class="user-card-label">{{$t('common.label.role')}}：</div>
            <div class="user-card-content">{{userData.roles}}</div>
          </div>
        </div>
        <div class="user-card-im" v-if="showIm&&userData.beOnTheJob">
          <div class="user-card-im-btn" @click="openMsg">{{$t('common.base.sendMessage')}}</div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import http from '@src/util/http';
import _ from 'lodash';
import { isOpenData, openAccurateTab } from '@src/util/platform';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import { getOssUrl } from '@src/util/assets'
const defaultAvatar = getOssUrl('avatar.png')
export default {
  name:'biz-user-card',
  data(){
    return {
      isOpenData,
      userId:'',
      show:false,
      userData:null,
      style:'',
      stateColor:{},
      showIm:false
    }
  },
  mounted(){
    document.addEventListener('click', this.handleClickOutside, false)
    http.get('/setting/getStateColorMap')
      .then(res => {this.stateColor = _.assign({}, this.stateColor, res || {})})
      .catch(err => console.error(err))
  },
  destroyed(){
    document.removeEventListener('click', this.handleClickOutside)
  },
  methods:{
    open(event, showCard = false){
      if(!event.user || !showCard) return
      this.userData = null
      this.userId = event.user.userId
      this.show = true
      let el = event.el.target || event.el
      this.$nextTick(()=>{
        if(el){
          let target = el.getBoundingClientRect()
          let topString = ''
          if((target.y + (this.$el.clientHeight / 2)) > window.innerHeight){
            topString = 'bottom:0px;'
          }else if(target.y < (this.$el.clientHeight / 2)){
            topString = 'top:0px;'
          }else{
            topString = `top:${target.y - (this.$el.clientHeight / 2)}px;`
          }
          if(target.x > 500){
            this.style = `left:${target.x - 360}px;${topString}`
          }else{
            this.style = `left:${target.x + target.width}px;${topString}`
          }
        }
      })
      this.initData(this.userId).then(res=>{
        if(el){
          this.$nextTick(()=>{
            let target = el.getBoundingClientRect()
            let topString = ''
            if((target.y + (this.$el.clientHeight / 2)) > window.innerHeight){
              topString = 'bottom:0px;'
            }else if(target.y < (this.$el.clientHeight / 2)){
              topString = 'top:0px;'
            }else{
              topString = `top:${target.y - (this.$el.clientHeight / 2)}px;`
            }
            if(target.x > 500){
              this.style = `left:${target.x - 360}px;${topString}`
            }else{
              this.style = `left:${target.x + target.width}px;${topString}`
            }
          })
        }
      })
    },
    head(src) {
      if (!src) return defaultAvatar
      return src
    },
    handleClickOutside(e){
      if(this.show && !this.$el.contains(e.target)) this.close();
    },
    close(){
      this.show = false
      this.userData = null
    },
    initData(userId){
      return new Promise((resolve, reject)=>{
        http.get('/api/user/outside/user/getUserCard', {cardUserId:userId}).then(res=>{
          this.userData = res.data
          this.showIm = res.data.showIm || false
          this.userData.roles = (this.userData.roleList?.fieldValues || []).join('，')
          resolve()
        })
      })
    },
    lookDynamics(){
      let fromId = window.frameElement?.getAttribute('id');
      openAccurateTab({
        type: PageRoutesTypeEnum.PageSecurityUserView,
        key: this.userId,
        fromId
      })
      parent.window.resizeFrame();
      this.$track.clickStat(this.$track.formatParams('VIEW_PERSONAL_CENTER'));
    },
    lookCalendar(){
      let {userName, displayName, userId, staffId, tenantId, head} = this.userData
      // localStorage.setItem('calendarTeam', JSON.stringify([{displayName, userId, staffId, tenantId, head}]))
      localStorage.setItem('calendarTeam', JSON.stringify([{displayName:userName, userId, staffId, tenantId, head}]))
      openAccurateTab({
        type: PageRoutesTypeEnum.PageSchedule,
        reload:true,
      })
      parent.window.resizeFrame();
    },
    openMsg(){
      if(!this.userId)return;
      parent?.window?.open_insideIM({
        userId:this.userId,
        url:location.href
      })
      this.close()
      this.$track.clickStat(this.$track.formatParams('IM_USER_SEND_MESSAGE'));
    }
  }
}
</script>
